<template>
  <div class="review-container">
    <basic-container v-show="!isDetail">
      <div class="top-box">
        <div class="top-left">
          <el-button type="primary" size="mini" plain @click="drawer = true">新建复盘</el-button>
          <el-button type="danger" size="mini" plain @click="delReviewReport(multipleSelection.map(item => item.id))">
            删除报告
          </el-button>
        </div>
        <i class="el-icon-refresh" @click="getReviewReportList"></i>
      </div>
      <div class="middle-box">
        <el-table
          :data="reviewReportList"
          stripe
          @selection-change="handleSelectionChange"
          ref="multipleTable"
          style="width: 100%"
          :header-cell-style="iHeaderCellStyle">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            type="index"
            label="#"
            width="50">
          </el-table-column>
          <el-table-column
            prop="name"
            label="报告名称">
          </el-table-column>
          <el-table-column
            label="复盘时间">
            <template v-slot="{ row }">
              <span>{{ row.startDate }} - {{ row.endDate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人">
            <template v-slot="{ row }">
              <span>
                {{ getUserNames(row.createUser) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === 0" size="mini" type="info">生成中</el-tag>
              <el-tag v-else-if="row.status === 1" size="mini" type="success">完成</el-tag>
              <el-tag v-else size="mini" type="warning">失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template v-slot="{row}">
              <template v-if="row.status === 1">
                <el-tooltip class="item" effect="dark" content="查看" placement="top">
                  <i class="el-icon-view" @click="showDetailById(row.id)"></i>
                </el-tooltip>
              </template>
              <template v-if="row.status !== 1">
                <el-tooltip class="item" effect="dark" content="重新生成" placement="top">
                <i class="el-icon-refresh" @click="refreshReport(row.id)"></i>
                </el-tooltip>
              </template>
              <template v-if="row.status !== 0">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i class="el-icon-delete" @click="delReviewReport([row.id])"></i>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </basic-container>
    <BaseDetail v-if="isDetail" @close="isDetail = false" :report-id="currentReportId"></BaseDetail>
    <el-drawer
      title="新增复盘"
      size="70%"
      :visible.sync="drawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      @close="handleCloseDrawer"
      ref="drawer"
    >
      <el-divider></el-divider>
      <div class="drawer-box" v-loading="drawerLoading">
        <el-form :model="addReportForm" :rules="rules" label-width="80px" ref="addReportFormRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="复盘名称" prop="name">
                <el-input size="mini" v-model="addReportForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="复盘时间" prop="selectDate">
                <el-date-picker
                  size="mini"
                  v-model="addReportForm.selectDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="drawer-bottom-btn">
          <el-button type="primary" size="mini" @click="addReviewReport">生成报告</el-button>
          <el-button size="mini" @click="drawer = false">取消</el-button>
        </div>

      </div>
    </el-drawer>
  </div>
</template>

<script>
import {dateFormat} from "@/util/date";
import {
  createReviewReport,
  queryReviewReportPage,
  removeReviewReportByIds,
  retryReviewReport
} from "@/api/dataReport/review-report";
// import {mapGetters} from "vuex";
import store from "@/store/";
import {createEventHandler} from "@/util/events";
import BaseDetail from "@/views/dataReport/review-report/BaseDetail";
import {getAllUser} from "@/api/user";
import {getList} from "@/api/business/offer";

export default {
  name: "ReviewReport",
  components: {
    BaseDetail
  },
  data() {
    const that = this
    return {
      offerId: store.state.user.offer,
      reviewReportList: [],
      queryInfo: {
        size: 10,
        current: 1
      },
      total: 0,
      drawer: false,
      addReportForm: {
        name: '',
        selectDate: []
      },
      multipleSelection: [],
      pickerOptions: {
        disabledDate(time) {
          // console.log(time.getTime())
          return time.getTime() < Date.parse(that.offerTime) - 3600 * 1000 * 24 || time.getTime() > Date.now() - 3600 * 1000 * 24;
        },
      },
      rules: {
        name: [
          {required: true, message: '请输入复盘名称', trigger: 'blur'},
          {max: 255, message: '最大支持长度 255 个字符', trigger: 'blur'}
        ],
        selectDate: [
          {required: true, message: '请选择日期', trigger: 'change'}
        ]
      },
      // 是否详情
      isDetail: false,
      // 当前详情ID
      currentReportId: '',
      // drawerloading
      drawerLoading: false,
      // 用户列表
      userList: [],
      offerTime: ''
    }
  },
  created() {
    getAllUser({statusList: '0,1,2'}).then(res => {
      this.userList = res.data.data
    })
    this.getReviewReportList()
    this.getOfferInfo()
    this.eventHandler = createEventHandler("offerCenter")
      .addListener(async (event) => {
        if (event.message === 'offerChanged' && event.offerId && event.offerId !== "") {
          this.offerId = event.offerId
          await this.getReviewReportList()
          this.isDetail = false
          await this.getOfferInfo()
        }
      });
  },
  computed: {
    // 获取offer
    // ...mapGetters(['offer'])
  },
  // watch: {
  //   'offerId': {
  //     handler: function (val, oldVal) {
  //       if (val !== oldVal) {
  //         this.getReviewReportList()
  //       }
  //     }
  //   }
  // },
  mounted() {

  },
  methods: {
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      this.queryInfo.size = val
      this.getReviewReportList()
    },
    handleCurrentChange(val) {
      this.queryInfo.current = val
      this.getReviewReportList()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 获取复盘数据
    async getReviewReportList() {
      this.queryInfo.offerId = this.offerId
      const {data: res} = await queryReviewReportPage(this.queryInfo)
      if (res.code !== 200) return
      this.reviewReportList = res.data.records
      this.total = res.data.total
    },
    // 添加复盘
    addReviewReport() {
      this.$refs.addReportFormRef.validate(async valid => {
        if (!valid) return
        this.drawerLoading = true
        this.addReportForm.startDate = this.addReportForm.selectDate[0]
        this.addReportForm.endDate = this.addReportForm.selectDate[1]
        this.addReportForm.offerId = this.offerId
        const {data: res} = await createReviewReport(this.addReportForm).catch(err => {
          this.drawerLoading = false
        })
        if (res.code !== 200) return
        this.drawer = false
        this.drawerLoading = false
        this.$message.success('新建复盘成功')
        await this.getReviewReportList()
      })
    },
    // 关闭新增复盘报告
    closeDrawer() {
      this.$refs.addReportFormRef.resetFields()
    },
    // 删除报告
    delReviewReport(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(this.multipleSelection)
        const idsStr = ids.join(',')
        const {data: res} = await removeReviewReportByIds({ids: idsStr})
        if (res.code !== 200) return this.$message.error('删除失败')
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        await this.getReviewReportList()
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消重新生成'
        // });
      });
    },
    showDetailById(id) {
      this.currentReportId = id
      this.isDetail = this

    },
    handleCloseDrawer() {
      this.addReportForm.name = ''
      this.addReportForm.selectDate = []
    },
    // 获取用户名
    getUserNames(userIds) {
      if (userIds != null && userIds != '' && this.userList != null && this.userList.length > 0) {
        let list = [];
        let ids = ('' + userIds).split(',');
        this.userList.forEach(user => {
          if (ids.includes(user.id)) {
            list.push(user.realName);
          }
        })
        return list.join(',');
      }
      return userIds;
    },
    // 查询当前订单属性
    async getOfferInfo() {
      const {data: res} = await getList(null, {
        id: this.offerId
      })
      // console.log('获取订单详情', res)
      this.offerTime = res.data.records[0].createTime.split(' ')[0]
    },
    // 重新生成报告
    refreshReport(id) {
      this.$confirm('是否重新生成报告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await retryReviewReport({id})
        if (res.code !== 200) return this.$message.error('数据生成失败')
        this.$message.success('数据重新生成中')
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消重新生成'
        // });
      })

    }
  }
}
</script>

<style lang="scss" scoped>
.review-container {
  .top-box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .top-right {
    }
  }

  .middle-box {
    margin-bottom: 10px;

    i {
      color: #34A9FF;
    }
  }

  .bottom-box {
    display: flex;
    justify-content: flex-end;
  }

  i {
    font-size: 16px;
    margin: 0 5px;
    cursor: pointer;
  }
}

.drawer-box {
  width: 100%;
  padding: 0 25px;
  height: 90%;

  .drawer-bottom-btn {
    text-align: center;
  }
}
</style>
